package com.example.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.common.base.BaseFragment
import com.example.common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviFragment <T:ViewDataBinding>:BaseFragment<T>(){
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        var rootview = super.onCreateView(inflater,container,savedInstanceState)
        initData()
        updateUi()
        EventBus.getDefault().register(this)
        return rootview
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event:CustomEvent){
        if(event!=null && event.target == this::class.java.simpleName){
            handEvent(event)
        }
    }

    open fun handEvent(event: CustomEvent){

    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }


    private fun updateUi(){
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUiState()
            }
        }
    }



    private fun initData(){
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED){
                sendViewIntent()
            }
        }
    }

    //发送意图
    open suspend fun sendViewIntent(){

    }
    //接受意图
    open suspend fun collectUiState(){

    }

}